import { Directive, Input, OnDestroy, TemplateRef, ViewContainerRef } from '@angular/core';
import { Store } from '@ngxs/store';
import { SystemSelector } from '../../store';
import { Subject, takeUntil } from 'rxjs';

@Directive({
  selector: '[ngxAuth]',
})
export class NgxAuthDirective implements OnDestroy {
  auth: any[] = [];
  destroy = new Subject<void>();

  @Input()
  set ngxAuth(authString: string) {
    this.auth.indexOf(authString) !== -1
        ? this.container.createEmbeddedView(this.templateRef)
        : this.container.clear();
  }

  constructor(
      private templateRef: TemplateRef<any>,
      private container: ViewContainerRef,
      private store: Store,
  ) {
    this.store.select(SystemSelector.authorities).pipe(takeUntil(this.destroy)).subscribe(r => {
      this.auth = r;
    });
  }

  ngOnDestroy(): void {
    this.destroy.next();
  }
}
